﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;
using System.Net;
using System.ComponentModel;
using System.IO;
using System.Diagnostics;
namespace Downloader
{
    public delegate void ProgressHandler(object sender, DownloadProgressChangedEventArgs e);
    public delegate void CompletedHandler(object sender, AsyncCompletedEventArgs e);
    public delegate void StartHandler(object e);

   public class ServiceDown
    {
        public enum Download_Status
        {
            Idle,
            Downloading,
            Error,
            Finish
        }

        public event ProgressHandler Progress;
        public event CompletedHandler Complete;
        public event StartHandler Start;


        public string Source { set; get; }
        public string Destination { set; get; }
        public string OriginalFileName { private set; get; }
        public Download_Status Status { private  set; get; }

        private NWebClient webClient;
        private string temp_name;
        private Uri _url;
        public ServiceDown()
        {
            Status = Download_Status.Idle;
        }

        public void Download()
        {
            if(Source == "" || Destination == "")
                iCompleted(this, new AsyncCompletedEventArgs(new Exception("Source or Destination empty"), true, null));

            try
            {
                webClient = new NWebClient();
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(iCompleted);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(iProgressChanged);
                temp_name = System.IO.Path.GetTempFileName();
                _url = new Uri(Source);
                webClient.DownloadFileAsync(_url, temp_name);
                
            }
            catch(Exception e)
            {
                iCompleted(this, new AsyncCompletedEventArgs(e,true,null));
                Status = Download_Status.Error;
            }

            iStart();
        }

        private void iProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(OriginalFileName))
                GetFilename();

            if (OriginalFileName == "")
                OriginalFileName = temp_name;

           if(Progress != null)
               Progress(this, e);
            
        }

        private void iCompleted(object sender, AsyncCompletedEventArgs e)
        {

            if (!string.IsNullOrEmpty(OriginalFileName))
            {
                if (File.Exists(Destination + "\\" + OriginalFileName))
                    try
                    {
                        File.Delete(Destination + "\\" + OriginalFileName);
                    }
                    catch (Exception f)
                    {
                        Exception g = new Exception(string.Format("no se Puede crear Archivo {0}",OriginalFileName));
                        AsyncCompletedEventArgs b = new AsyncCompletedEventArgs(g, true, e.UserState);
                        Complete(this, b);
                        Status = Download_Status.Error;
                        return;
                    }
                File.Move(temp_name, Destination + "\\" + OriginalFileName);
            }

            if (Complete != null)
            {
                Status = Download_Status.Finish;
                Complete(this, e);
            }
        }

        private void iStart()
        {
            if (Start != null)
            {
                Status = Download_Status.Downloading;
                Start(this);
            }
        }

        private void GetFilename()
        {
            
            if (webClient.ResponseHeaders["content-disposition"] != null)
            {
                OriginalFileName = webClient.ResponseHeaders["content-disposition"];
            }else{
                OriginalFileName = webClient.FullUrl.LocalPath.TrimStart('/');
                OriginalFileName = Path.GetFileName(OriginalFileName);
            }
        }
   }

}
